package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"perm-guard/cache"
	"perm-guard/models"
	"perm-guard/pkg"
	"strconv"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	login_key := "login_key" + username
	errcount, _ := cache.Rdb.Get(cache.Ctx, login_key).Int()
	if errcount > 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误三次",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}
	err = models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "角色不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	} else {
		token, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
		c.JSON(http.StatusOK, gin.H{
			"code":  200,
			"msg":   "登录成功",
			"token": token,
		})
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var Role []models.Role
	list_key := "list_key" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Offset(offset).Limit(size).Find(&Role)
		cachedata, _ := json.Marshal(&Role)
		cache.Rdb.Set(cache.Ctx, list_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &Role)
	}
	var total int64
	models.DB.Model(&models.User{}).Count(&total)
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  Role,
		"total": total,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var role models.Role
	detail_key := "detail_key" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&role)
		cachedata, _ := json.Marshal(role)
		cache.Rdb.Set(cache.Ctx, detail_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &role)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}
